<template>
<el-tabs
	v-model="editableTabsValue"
	type="border-card"
	@tab-remove="removeTab"
	@tab-change="handleClick2"
>

	<el-tab-pane name="00">
		<template #label>
        <span class="custom-tabs-label">
          <el-icon><HomeFilled /></el-icon>
          <span>菜单栏</span>
        </span>
		</template>

		<el-menu>
			<el-menu-item index="1" @click="update_password()"><el-icon><UserFilled /></el-icon>用户名: {{ store.username }}</el-menu-item>
			<el-menu-item index="2" @click="quit()"><el-icon><CircleCloseFilled /></el-icon>退出登录</el-menu-item>
			<div class="flex-grow"/>

			<el-sub-menu index="库存管理">
				<template #title><el-icon><Menu /></el-icon>库存管理</template>
        <el-menu-item index="导出" @click="toPage('Export')" v-if="temp1.includes('Export')"><el-icon><Setting /></el-icon>导出</el-menu-item>
				<el-menu-item index="物料分组" @click="toPage('MaterialGroup')" v-if="temp1.includes('MaterialGroup')"><el-icon><Setting /></el-icon>物料分组</el-menu-item>
        <el-menu-item index="物料" @click="toPage('Material')" v-if="temp1.includes('Material')"><el-icon><Setting /></el-icon>物料</el-menu-item>
        <el-menu-item index="处理方分组" @click="toPage('HandleGroup')" v-if="temp1.includes('HandleGroup')"><el-icon><Setting /></el-icon>处理方分组</el-menu-item>
        <el-menu-item index="处理方" @click="toPage('Handle')" v-if="temp1.includes('Handle')"><el-icon><Setting /></el-icon>处理方</el-menu-item>
        <el-menu-item index="出入库记录" @click="toPage('Record')" v-if="temp1.includes('Record')"><el-icon><Setting /></el-icon>出入库记录</el-menu-item>
        <el-menu-item index="出入库" @click="toPage('InOut')" v-if="temp1.includes('InOut')"><el-icon><Setting /></el-icon>出入库</el-menu-item>
			</el-sub-menu>

			<el-sub-menu index="管理">
				<template #title><el-icon><Menu /></el-icon>管理应用</template>
				<el-menu-item index="用户管理" @click="toPage('PersonnelManagement')" v-if="temp1.includes('PersonnelManagement')">
					<el-icon><User /></el-icon>用户管理
				</el-menu-item>
			</el-sub-menu>

		</el-menu>

	</el-tab-pane>

	<el-tab-pane
		v-for="item in editableTabs"

		:key="item.name"
		lazy
		:label="item.title"
		:name="item.name"
		:closable="item.closable"
	>
		<component :is="item.component" />
	</el-tab-pane>



</el-tabs>


<!-- 修改密码 -->
<el-dialog v-model="update_password_dialog_visible"
					 :title=" '修改密码' "
					 :close-on-click-modal='false'
					 :close-on-press-escape='false'
					 :show-close='false'>

	<el-form :model="update_password_value" :rules="update_password_dialog_rules" ref="update_password_dialog_ref" :label-position=" 'right' " label-width="90px">
		<!-- :rules="rules" -->

		<el-form-item prop="password" label="新密码">
			<el-input v-model="update_password_value.password" autocomplete="off"/>
		</el-form-item>

	</el-form>
	<template #footer>
      <span class="dialog-footer">
        <el-button @click="update_password_dialog_visible = false; update_password_value.password='' ">取消</el-button>
        <el-button type="primary" @click="change_password()">
          保存
        </el-button>
      </span>
	</template>
</el-dialog>














</template>
<script lang="ts" setup>
import {
	Setting,
	User,
	UserFilled,
	Menu, CircleCloseFilled, HomeFilled,
} from '@element-plus/icons-vue'

import {reactive, ref, markRaw, onMounted} from 'vue'
import MaterialGroup from "@/page/inventory/MaterialGroup/MaterialGroup.vue";
import Material from "@/page/inventory/Material/Material.vue";
import PersonnelManagement from "@/page/manage/PersonnelManagement.vue";

import {useStore} from '@/pinia'
const store = useStore()
import {useRouter} from "vue-router";
import {ElMessage, FormRules} from "element-plus";
import {TokenRefreshResponse, UpdateUserInfoResponse} from "@/api/manage/personnelManagement/type.ts";
import {reqTokenExtended, reqUpdateUser} from "@/api/manage/personnelManagement";
import Handle from "@/page/inventory/Handle/Handle.vue";
import HandleGroup from "@/page/inventory/HandleGroup/HandleGroup.vue";
import Record from "@/page/inventory/Record/Record.vue";
import InOut from "@/page/inventory/InOut/InOut.vue";
import Export from "@/page/inventory/ExportTable/Export.vue";

// 在该页面被打开的时候进行检查，查看token是否合法，避免token过期
onMounted(()=>{
  if (localStorage.getItem('token')) {
    reqTokenExtended({}).then((res: TokenRefreshResponse)=>{
      localStorage.setItem('token', res.data)
    })
  }
})


const update_password_dialog_rules = reactive<FormRules>({
	password: [{
		type: 'string',
		message: '密码长度小于等于10',
		max: 10,
		min: 1,
		required: true
	}],
})
const update_password_value = reactive({
	password: ''
})
const update_password_dialog_ref = ref()
const update_password_dialog_visible = ref(false)
// 修改密码
const update_password = () => {
	update_password_dialog_visible.value = true
	update_password_dialog_ref.value?.clearValidate()
}
const change_password = async () => {
	update_password_dialog_visible.value = false

	await update_password_dialog_ref.value?.validate()
	const result: UpdateUserInfoResponse = await reqUpdateUser({
		username: store.username,
		password: update_password_value.password.trim(),
		creator: store.username,
		id: store.user_id,
	})
	ElMessage.success(`${result.success?.message}, 请重新登录`)
	await router.push({name: 'login'})
}

const router = useRouter()
const temp1: string[] = store.permissions

const all_tabs:any = {
	'MaterialGroup': {'name': '物料分组', 'component': MaterialGroup},
	'Material': {'name': '物料', 'component': Material},
	'Handle': {'name': '处理方', 'component': Handle},
	'HandleGroup': {'name': '处理方分组', 'component': HandleGroup},
	'Record': {'name': '出入库记录', 'component': Record},
	'InOut': {'name': '出入库', 'component': InOut},
	'Export': {'name': '导出', 'component': Export},

	'PersonnelManagement': {'name': '权限管理', 'component': PersonnelManagement},
}

const editableTabsValue = ref('00')
const editableTabs = ref<{
	title: any
	name: string
	closable: boolean
	component: any
}[]>([])

const toPage = (tabName: string) => {
	store.axios_path = tabName.slice(-1)

	// 队列中的组件超过六个的时候自动报警
	if(editableTabs.value.length >= 6){
		ElMessage.info('标签页超过8个，请关闭一些标签页再打开新的标签页')
		return
	}
	// 首先检查要添加的组件是否已经存在于队列之中
	for(let i of editableTabs.value){
		if(i.name === tabName){
			editableTabsValue.value = i.name
			return
		}
	}
	// 将组件加入队列
	editableTabs.value.push({
		title: all_tabs[tabName].name,
		name: tabName,
		closable: true,
		// 使用shallowRef节省性能开销
		component: markRaw(all_tabs[tabName].component),
	})
	editableTabsValue.value = tabName

}

// 删除页签
const removeTab = (targetName: string) => {
	const tabs = editableTabs.value  // 所有在列表中的页签
	let activeName = editableTabsValue.value  //

	if (activeName === targetName) {
		tabs.forEach((tab, index) => {
			if (tab.name === targetName) {
				const nextTab = tabs[index + 1] || tabs[index - 1]
				if (nextTab) {
					activeName = nextTab.name
          store.axios_path = activeName.slice(-1)
				}
			}
		})
	}
	editableTabsValue.value = activeName
	editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
	if(editableTabs.value.length === 0){
		editableTabsValue.value = '00'
    store.axios_path = activeName.slice(-1)
	}
}

// 退出
const quit = () => {
	// 清空token
	localStorage.removeItem('token')
	sessionStorage.removeItem('token')
	// pinia恢复初始值
	store.$reset()
	ElMessage.success('登录退出成功')
	router.push({ name: 'login' })
}

// 打印当前所在的页签
const handleClick2 = (tab: string) => {
	store.axios_path = tab.slice(-1)
}
</script>

<style scoped>
.custom-tabs-label .el-icon {
	vertical-align: middle;
}
.custom-tabs-label span {
	vertical-align: middle;
	margin-left: 4px;
}
</style>
